package org.amf.channel;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * La classe HTTPChannel inizializza il canale
 * di comunicazione HTTP
 *
 * @author Federico Casani
 */
public class HTTPChannel {

    private int statusResponse = 0;

    public HTTPChannel(String urlString, byte[] message) {


        try {
            /*
             * HTTP POST
             */
            boolean isMessageOk = (message!=null && message.length>0) ? true :false;
            boolean isUrlStringOk = (urlString!=null && urlString.length()>0) ? true :false;

            if (isUrlStringOk && isMessageOk) {

                URL httpURL = new URL(urlString);

                HttpURLConnection httpURLConnection =  (HttpURLConnection) httpURL.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setUseCaches(true);
                httpURLConnection.setDefaultUseCaches(true);
                httpURLConnection.setRequestProperty("Content-Length", String.valueOf(message.length));
                httpURLConnection.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(message);
                outputStream.close();

                statusResponse = httpURLConnection.getResponseCode();
            } 
            
        } catch (Exception e) {
            
            this.statusResponse = 0;
        }


    }

    public int getStatusResponse() {
        return statusResponse;
    }

}
